package com.hyperfix.gateway.filter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hyperfix.utils.common.auth.WhiteURLRegistrar;
import com.hyperfix.utils.common.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hyperfix.models.constant.common.LoginConstant.*;

@Component
@Slf4j
public class AuthorizeFilter implements Ordered, GlobalFilter {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 登录 验证码 找回密码 放行
        String path = request.getURI().getPath();
        if (WhiteURLRegistrar.isWhiteURL(path)) {
            return chain.filter(exchange);
        }
        String token = null;
        if (path.contains(WhiteURLRegistrar.WS_URL)) {
            List<String> subProtocols = request.getHeaders().get("Sec-WebSocket-Protocol");
            if (subProtocols != null) {
                token = subProtocols.get(0);
            }
        } else {
            token = request.getHeaders().getFirst("token");
        }
        // 判断token是否存在
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 判断token是否合法
        try {
            Claims claimsBody = JwtUtil.parseJWT(token);
            String username = claimsBody.getSubject();
            String key = LOGIN_KEY_PREFIX + username;
            String tokenInRedis = stringRedisTemplate.opsForValue().get(key);
            if (StringUtils.isBlank(token) || !token.equals(tokenInRedis)) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            String userKey = LOGIN_USER_PREFIX + username;
            // 续期
            Long expire = stringRedisTemplate.getExpire(key, TimeUnit.HOURS);
            if (expire != null && expire < LOGIN_REFRESH_HOUR) {
                stringRedisTemplate.expire(key, LOGIN_TTL_DAY, TimeUnit.DAYS);
            }
            Long userExpire = stringRedisTemplate.getExpire(userKey, TimeUnit.HOURS);
            if (userExpire != null && userExpire < LOGIN_REFRESH_HOUR) {
                stringRedisTemplate.expire(userKey, LOGIN_TTL_DAY, TimeUnit.DAYS);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        return chain.filter(exchange);
    }

    /**
     * 优先级设置  值越小  优先级越高
     *
     * @return int
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
